package io.finer.erp.jeecg.stock.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Dict;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.ProcessConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.util.dingtalk.DingTalkUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiProcessinstanceCreateRequest;
import com.dingtalk.api.request.OapiProcessinstanceCreateRequest.FormComponentValueVo;
import com.dingtalk.api.response.OapiProcessinstanceCreateResponse;
import com.taobao.api.ApiException;

import io.finer.erp.jeecg.bas.dto.MaterialContrastDTO;
import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.finance.dto.CustomerGrossDetailDTO;
import io.finer.erp.jeecg.finance.dto.CustomerGrossProfitDTO;
import io.finer.erp.jeecg.finance.dto.GrossProfitDetailDTO;
import io.finer.erp.jeecg.finance.dto.GrossProfitSummaryDTO;
import io.finer.erp.jeecg.finance.vo.PurchaseOrderVO;
import io.finer.erp.jeecg.stock.dto.StkEntryDetailDTO;
import io.finer.erp.jeecg.stock.dto.StkIoBillEntryDTO;
import io.finer.erp.jeecg.stock.dto.StkPurchaseOrderDTO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.service.IErpSysUserService;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;
import io.finer.erp.jeecg.stock.vo.StkIoBillPage;
import io.finer.erp.jeecg.stock.vo.StkIoBillVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: 出入库单
 * @Author: jeecg-boot
 * @Date:   2020-03-31
 * @Version: V1.0
 */
@Api(tags="出入库单")
@RestController
@RequestMapping("/stock/stkIoBill")
@Slf4j
public class StkIoBillController {
	@Autowired
	private IStkIoBillService stkIoBillService;
	@Autowired
	private IStkIoBillEntryService stkIoBillEntryService;
	@Autowired
	private IBasMaterialService basMaterialService;
	@Autowired
	private IErpSysUserService userService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IBasMaterialCategoryService basMaterialCategoryService;

	/**
	 * 分页列表查询
	 *
	 * @param stkIoBill
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "出入库单-分页列表查询")
	@ApiOperation(value="出入库单-分页列表查询", notes="出入库单-分页列表查询")
	@GetMapping(value = {"/list",
			"/list/{stockIoType}",
	"/list/{stockIoType}/{isRubric}"})  //stockIoType会传至stkIoBill.stockIoType
	public Result<?> queryPageList(StkIoBill stkIoBill,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		QueryWrapper<StkIoBill> queryWrapper;
		String stockIoType = stkIoBill.getStockIoType();
		String[] stockIoTypes = null;
		stkIoBill.setStockIoType(null);
		if (StringUtils.isNotBlank(stockIoType)) {
			stockIoTypes = StringUtils.split(stockIoType, "A");
		}
		queryWrapper = QueryGenerator.initQueryWrapper(stkIoBill, req.getParameterMap());
		if (stockIoTypes != null && 1 == stockIoTypes.length) {
			queryWrapper.eq("stock_io_type", stockIoType);
		} else if (stockIoTypes != null && 1 < stockIoTypes.length) {
			queryWrapper = new QueryWrapper<>();
			List<String> list = Arrays.asList(stockIoTypes);
			queryWrapper.in("stock_io_type", list);
		}
		queryWrapper.orderByDesc("create_time");
		
		Page<StkIoBill> page = new Page<StkIoBill>(pageNo, pageSize);
		IPage<StkIoBill> pageList = stkIoBillService.page(page, queryWrapper);
		return Result.ok(pageList);
	}

	@AutoLog(value = "出入库单-字典查询")
	@ApiOperation(value="出入库单-字典查询", notes="出入库单-字典查询")
	@GetMapping(value = {"/listDict",
			"/listDict/{stockIoType}",
	"/listDict/{stockIoType}/{isRubric}"})  //stockIoType会传至stkIoBill.stockIoType
	public Result<?> query201List(StkIoBill stkIoBill,HttpServletRequest req) {
		List<Dict> list=new ArrayList<Dict>();
		Map<String,Object> columnMap=new HashMap<String,Object>();
		columnMap.putIfAbsent("stock_io_type", stkIoBill.getStockIoType());
		Collection<StkIoBill> col=stkIoBillService.listByMap(columnMap);
		if(null!=col&&col.size()>0) {
			Iterator<StkIoBill> iterator=col.iterator();
			while(iterator.hasNext()) {
				StkIoBill sib=iterator.next();
				Dict dict=new Dict();
				dict.setText(sib.getBillNo());
				dict.setValue(sib.getId());
				list.add(dict);
			}
		}
		return Result.ok(list);
	}
	
	@AutoLog(value = "销售出库明细-字典查询")
	@ApiOperation(value="销售出库明细-字典查询", notes="销售出库明细-字典查询")
	@GetMapping(value = {"/query201ListDetails"}) 
	public Result<?> query201ListDetails(StkIoBill stkIoBill,HttpServletRequest req) {
		List<Dict> list=new ArrayList<Dict>();
		Map<String,Object> columnMap=new HashMap<String,Object>();
		//billNo存的为销售出库ID
		StkIoBill stkIoBi=stkIoBillService.getById(stkIoBill.getBillNo());
		columnMap.putIfAbsent("bill_no", stkIoBi.getBillNo());
		Collection<StkIoBillEntry> col=stkIoBillEntryService.listByMap(columnMap);
		if(null!=col&&col.size()>0) {
			Iterator<StkIoBillEntry> iterator=col.iterator();
			while(iterator.hasNext()) {
				StkIoBillEntry sib=iterator.next();
				//查询产品信息
				BasMaterial basMaterial=basMaterialService.getById(sib.getMaterialId());
				Dict dict=new Dict();
				//设置text为产品名称
				dict.setText(basMaterial.getName());
				//设置balue为产品ID
				dict.setValue(sib.getId());
				list.add(dict);
			}
		}
		return Result.ok(list);
	}


	/**
	 *   添加
	 *
	 * @param stkIoBillPage
	 * @return
	 */
	@AutoLog(value = "出入库单-添加")
	@ApiOperation(value="出入库单-添加", notes="出入库单-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody StkIoBillPage stkIoBillPage) {
		StkIoBill stkIoBill = new StkIoBill();
		BeanUtils.copyProperties(stkIoBillPage, stkIoBill);
//		if(stkIoBillPage.getStockIoType().equals("101")) {
//			//只有发起采购单时才需要走审批流程
//			String flowId=generateProduceApply(stkIoBillPage);
//			stkIoBill.setFlowId(flowId);//关联流程ID
//		}
		if(stkIoBillPage.getStockIoType().equals("601")) {
			//添加采购时赋值一个默认的仓库以避免报错
			List<StkIoBillEntry> entryList = stkIoBillPage.getStkIoBillEntryList();
			if (null != entryList && 0 != entryList.size()) {
				for (StkIoBillEntry stkIoBillEntry : entryList) {
					stkIoBillEntry.setWarehouseId("601HouseId");
				}
			}
			stkIoBill.setHasRp(0);
			//只有发起采购单时才需要走审批流程
			String flowId=generateProduceApply(stkIoBillPage);
			stkIoBill.setFlowId(flowId);//关联流程ID
		}
		System.out.println(JSONObject.toJSONString(stkIoBillPage));
		stkIoBillService.saveMain(stkIoBill, stkIoBillPage.getStkIoBillEntryList());
		return Result.ok("添加成功！");
	}
	
	@AutoLog(value = "采购单审批")
	@ApiOperation(value="采购单审批", notes="采购单审批")
	@PostMapping(value = "/purchaseApproval")
	public Result<?> purchaseApproval(@RequestParam("flowId") String flowId, @RequestParam("status") String status){
		LambdaQueryWrapper<StkIoBill> query = new LambdaQueryWrapper<StkIoBill>();
		query.eq(StkIoBill::getFlowId, flowId);
		query.eq(StkIoBill::getStockIoType, "601");
		StkIoBill bill = this.stkIoBillService.getOne(query);
		if (null == bill) {
			return Result.error("未找到采购单");
		}
		bill.setBillProcStatus(status);
		bill.setIsApproved(1);//审核完成
		boolean flag = this.stkIoBillService.updateById(bill);
		if (flag) {
			return Result.ok("审批完成");
		} else {
			return Result.error("审批失败");
		}
	}
	
	/**
	 * @description 库存管理所有申请单，此处只是模拟使用钉钉接口，真正项目中需要配合小程序实现获取登录用户信息然后更新方法中setOriginatorUserId
	 * @param args
	 * @param process_code=PROC-DC326BC5-F99D-4D3B-A8C9-FD3464CCCCD3
	 * @return {"errcode":0,"process_instance_id":"2a094e5f-f1dc-4caa-b3fb-39c9ff0e96ce","request_id":"phqg6rhc8mjx"}
	 */
	private String generateProduceApply(StkIoBillPage stkIoBillPage) {
		String flowId="00001";
		try {
			DingTalkClient client = new DefaultDingTalkClient(ProcessConstant.URL_CREATEPROCESS);
			OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
			req.setAgentId(new Long(ProcessConstant.AGENTID));
			req.setProcessCode(ProcessConstant.KCPROCESSCODE);
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			String thirdId = userService.getUserThirdId(sysUser.getId());
			req.setOriginatorUserId(thirdId);
			req.setDeptId(-1L);
			List<FormComponentValueVo> list2 = new ArrayList<FormComponentValueVo>();
			FormComponentValueVo obj12 = new FormComponentValueVo();
			list2.add(obj12);
			obj12.setName("单据类型");
			obj12.setValue("采购单");
			
			FormComponentValueVo obj = new FormComponentValueVo();
			list2.add(obj);
			obj.setName("申请时间");
			obj.setValue(DateUtils.getDate("yyyy-MM-dd HH:mm"));
			
			FormComponentValueVo obj13 = new FormComponentValueVo();
			list2.add(obj13);
			obj13.setName("业务员");
			obj13.setValue(stkIoBillPage.getClerkId());
			
			FormComponentValueVo obj14 = new FormComponentValueVo();
			list2.add(obj14);
			obj14.setName("经办人");
			obj14.setValue(stkIoBillPage.getHandlerId()==null?" ":stkIoBillPage.getHandlerId());
			
			FormComponentValueVo obj15 = new FormComponentValueVo();
			list2.add(obj15);
			obj15.setName("原单类型");
			obj15.setValue("销售订单");
			
			FormComponentValueVo obj16 = new FormComponentValueVo();
			list2.add(obj16);
			obj16.setName("原单号");
			obj16.setValue(stkIoBillPage.getSourceNo()==null?" ":stkIoBillPage.getSourceNo());
			
			//计算申请总金额
			List<StkIoBillEntry> stkIoBillEntryList=stkIoBillPage.getStkIoBillEntryList();
			String materialDetails="";
			BigDecimal total=BigDecimal.ZERO;
			if(null!=stkIoBillEntryList&&stkIoBillEntryList.size()>0) {
				for(StkIoBillEntry sbe:stkIoBillEntryList) {
					total=total.add(sbe.getSettleAmt());
					BasMaterialCategory bmc=basMaterialCategoryService.getById(sbe.getMaterialId());//此处material_id存储的为物料分类ID，注意别取错了
					if(materialDetails.equals("")) {
						materialDetails=bmc.getName()+" 数量:"+sbe.getQty();
					}else {
						materialDetails+=","+bmc.getName()+" 数量:"+sbe.getQty();
					}
				}
			}
			
			FormComponentValueVo obj20 = new FormComponentValueVo();
			list2.add(obj20);
			obj20.setName("申请金额");
			obj20.setValue(total+"");

			FormComponentValueVo obj2 = new FormComponentValueVo();
			list2.add(obj2);
			obj2.setName("备注");
			obj2.setValue(materialDetails);
			
//			/**开始拼接明细**/
//			//下拉
//		    FormComponentValueVo obj4 = new FormComponentValueVo();
//		    obj4.setName("货品名称");
//		    obj4.setValue("73克中档黄不打印（汇利）");
//		    
//		    //下拉
//		    FormComponentValueVo obj5 = new FormComponentValueVo();
//		    obj5.setName("计量单位");
//		    obj5.setValue("平方");
//		    
//		    FormComponentValueVo obj6 = new FormComponentValueVo();
//		    obj6.setName("入库数量");
//		    obj6.setValue("2123");
//		    
//		    FormComponentValueVo obj7 = new FormComponentValueVo();
//		    obj7.setName("入库成本");
//		    obj7.setValue("4.5");
//		    
//		    FormComponentValueVo obj8 = new FormComponentValueVo();
//		    obj8.setName("成本含税");
//		    obj8.setValue("是");
//		    
//		    FormComponentValueVo obj9 = new FormComponentValueVo();
//		    obj9.setName("仓库");
//		    obj9.setValue("0101仓库");
//		    
//		    FormComponentValueVo obj10 = new FormComponentValueVo();
//		    obj10.setName("批次号");
//		    obj10.setValue("202008120001");
//		    
//		    FormComponentValueVo obj17 = new FormComponentValueVo();
//		    obj17.setName("结算数量");
//		    obj17.setValue("200");
//		    
//		    FormComponentValueVo obj18 = new FormComponentValueVo();
//		    obj18.setName("含税单价");
//		    obj18.setValue("205");
//		    
//		    FormComponentValueVo obj19 = new FormComponentValueVo();
//		    obj19.setName("税率");
//		    obj19.setValue("0.01");
//		    
//		    FormComponentValueVo obj20 = new FormComponentValueVo();
//		    obj20.setName("税额");
//		    obj20.setValue("5");
//		    
//		    FormComponentValueVo obj21 = new FormComponentValueVo();
//		    obj21.setName("折让金额");
//		    obj21.setValue("5");
//		    
//		    FormComponentValueVo obj22 = new FormComponentValueVo();
//		    obj22.setName("折让税额");
//		    obj22.setValue("0.01");
//		    
//		    FormComponentValueVo obj11 = new FormComponentValueVo();
//		    obj11.setName("结算金额");
//		    obj11.setValue("200");
//			
//		    // 明细
//		    OapiProcessinstanceCreateRequest.FormComponentValueVo vo4 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//		    vo4.setName("采购明细");
//		    vo4.setValue(JSON.toJSONString(Arrays.asList(Arrays.asList(obj4, obj5, obj6,obj7,obj8,obj9,obj10,obj17,obj18,obj19,obj20,obj21,obj22,obj11))));
//		    list2.add(vo4);
//			/**明细结束**/
			req.setFormComponentValues(list2);
			//获取token,真正发起调用  a1bb9cccbe2034f5848202a7391b4d7d
			OapiProcessinstanceCreateResponse rsp = client.execute(req, DingTalkUtils.get_token());
			System.out.println(rsp.getProcessInstanceId());
			flowId=rsp.getProcessInstanceId();
		} catch (ApiException e) {
		}
		return flowId;
	}
	

	/**
	 *  编辑
	 *
	 * @param stkIoBillPage
	 * @return
	 */
	@AutoLog(value = "出入库单-编辑")
	@ApiOperation(value="出入库单-编辑", notes="出入库单-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody StkIoBillPage stkIoBillPage) {
		StkIoBill stkIoBill = new StkIoBill();
		BeanUtils.copyProperties(stkIoBillPage, stkIoBill);
		StkIoBill stkIoBillEntity = stkIoBillService.getById(stkIoBill.getId());
		if(stkIoBillEntity==null) {
			return Result.error("未找到对应数据");
		}
		if(stkIoBill.getStockIoType().equals("601")) {
			List<StkIoBillEntry> stkIoBillEntryList = stkIoBillPage.getStkIoBillEntryList();
			if(null != stkIoBillEntryList && 0 != stkIoBillEntryList.size()){
				for (StkIoBillEntry stkIoBillEntry : stkIoBillEntryList) {
					stkIoBillEntry.setWarehouseId("601HouseId");
				}
			}
			stkIoBill.setHasRp(0);
			this.sysBaseAPI.insertPurchaseOrderJobQueue(stkIoBill.getId());
			
		}
		stkIoBillService.updateMain(stkIoBill, stkIoBillPage.getStkIoBillEntryList());
		return Result.ok("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出入库单-通过id删除")
	@ApiOperation(value="出入库单-通过id删除", notes="出入库单-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		stkIoBillService.delMain(id);
		return Result.ok("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "出入库单-批量删除")
	@ApiOperation(value="出入库单-批量删除", notes="出入库单-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.stkIoBillService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "出入库单-通过id查询")
	@ApiOperation(value="出入库单-通过id查询", notes="出入库单-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		StkIoBill stkIoBill = stkIoBillService.getById(id);
		if(stkIoBill==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(stkIoBill);

	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "明细集合-通过id查询")
	@ApiOperation(value="明细集合-通过id查询", notes="明细-通过id查询")
	@GetMapping(value = "/queryEntryByMainId")
	public Result<?> queryEntryListByMainId(@RequestParam(name="id",required=true) String id) {
		List<StkIoBillEntry> stkIoBillEntryList = stkIoBillEntryService.selectByMainId(id);
		return Result.ok(stkIoBillEntryList);
	}

	@AutoLog(value = "明细集合-通过id查询")
	@ApiOperation(value="明细集合-通过id查询", notes="明细-通过id查询")
	@GetMapping(value = "/queryEditingEntryByMainId")
	public Result<?> queryEditingEntryListByMainId(@RequestParam(name="id",required=true) String id) {
		List<StkIoBillEntry> stkIoBillEntryList = stkIoBillEntryService.selectEditingByMainId(id);
		return Result.ok(stkIoBillEntryList);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param stkIoBill
	 */
	@RequestMapping(value = {"/exportXls", "/exportXls/{stockIoType}"})  //stockIoType会传至stkIoBill.stockIoType
	public ModelAndView exportXls(HttpServletRequest request, StkIoBill stkIoBill) {
		// Step.1 组装查询条件查询数据
		QueryWrapper<StkIoBill> queryWrapper = QueryGenerator.initQueryWrapper(stkIoBill, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<StkIoBill> queryList = stkIoBillService.list(queryWrapper);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<StkIoBill> stkIoBillList = new ArrayList<StkIoBill>();
		if(oConvertUtils.isEmpty(selections)) {
			stkIoBillList = queryList;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			stkIoBillList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}

		// Step.3 组装pageList
		List<StkIoBillPage> pageList = new ArrayList<StkIoBillPage>();
		for (StkIoBill main : stkIoBillList) {
			StkIoBillPage vo = new StkIoBillPage();
			BeanUtils.copyProperties(main, vo);
			List<StkIoBillEntry> stkIoBillEntryList = stkIoBillEntryService.selectByMainId(main.getId());
			vo.setStkIoBillEntryList(stkIoBillEntryList);
			pageList.add(vo);
		}

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "出入库单列表");
		mv.addObject(NormalExcelConstants.CLASS, StkIoBillPage.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("出入库单数据", "导出人:"+sysUser.getRealname(), "出入库单"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}
	
	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<StkIoBillPage> list = ExcelImportUtil.importExcel(file.getInputStream(), StkIoBillPage.class, params);
				for (StkIoBillPage page : list) {
					StkIoBill po = new StkIoBill();
					BeanUtils.copyProperties(page, po);
					stkIoBillService.saveMain(po, page.getStkIoBillEntryList());
				}
				return Result.ok("文件导入成功！数据行数:" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入失败！");
	}

	@AutoLog(value = "出入库单-通过id审核")
	@ApiOperation(value="出入库单-通过id审核", notes="出入库单-通过id审核")
	@PutMapping(value = "/approve")
	public Result<?> approve(@RequestBody JSONObject json) {
		stkIoBillService.approve(json.getString("id"));
		return Result.ok("审核通过!");
	}

	@AutoLog(value = "重新编辑销售单")
	@ApiOperation(value="重新编辑销售单", notes="重新编辑销售单")
	@GetMapping(value = "/reEdit")
	public Result<?> reEdit(@RequestParam(name = "billId", required = true)String billId
			, @RequestParam(name = "ioType", required = true)String ioType){
		if(!"601".equals(ioType)) {
			return Result.error(500, "只有采购单才可以重新编辑");
		}
		LambdaQueryWrapper<StkIoBill> query = new LambdaQueryWrapper<>();
		query.eq(StkIoBill::getId, billId).eq(StkIoBill::getStockIoType, ioType);
		
		StkIoBill bill = this.stkIoBillService.getOne(query);
		if(null == bill) {
			return Result.error(500, "未找到该销售单");
		}
		bill.setBillProcStatus("12");
		bill.setIsApproved(0);
		boolean flag = this.stkIoBillService.updateById(bill);
		if(flag) {
			return Result.ok("操作成功");
		} else {
			return Result.error(500, "操作失败");
		}
	}
	
	/**
	 * @Description 采购单（供应商）列表汇总查询
	 * @param stkIoBill
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 * Create at: 2021-05-05 10:02:44
	 * @author: xzs
	 * Revision:
	 *    2021-05-05 10:02:44 - first revision by xzs
	 *        
	 */
	@AutoLog(value = "采购单（供应商）列表查询")
	@ApiOperation(value="采购单（供应商）列表查询", notes="采购单（供应商）列表查询")
	@GetMapping(value = "/querylistBySupplier") 
	public Result<?> querylistBySupplier(StkIoBillVO stkIoBillVO,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		Page<StkPurchaseOrderDTO> page = new Page<StkPurchaseOrderDTO>(pageNo, pageSize);
		List<StkPurchaseOrderDTO> list = stkIoBillService.querylistBySupplier(stkIoBillVO);
		return Result.ok(page.setRecords(list));
	}
	
	/**
	 * 采购单（供应商）列表汇总导出excel
	 *
	 * @param request
	 * @param stkIoBill
	 */
	@RequestMapping(value = {"/exportBillSupplierXls"}) 
	public ModelAndView exportBillSupplierXls(HttpServletRequest request, StkIoBillVO stkIoBillVO) {
		// Step.1 当前登录人
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<StkPurchaseOrderDTO> list = stkIoBillService.querylistBySupplier(stkIoBillVO);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<StkPurchaseOrderDTO> dtoList = new ArrayList<StkPurchaseOrderDTO>();
		if(oConvertUtils.isEmpty(selections)) {
			dtoList = list;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			dtoList = list.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}


		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "采购单（供应商）列表汇总");
		mv.addObject(NormalExcelConstants.CLASS, StkPurchaseOrderDTO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采购单（供应商）列表汇总", "导出人:"+sysUser.getRealname(), "采购单（供应商）列表汇总"));
		mv.addObject(NormalExcelConstants.DATA_LIST, dtoList);
		return mv;
	}
	
	/**
	 * @Description 采购单（供应商）列表汇总详情
	 * @param stkIoBillVO
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 * Create at: 2021-08-25 17:26:04
	 * @author: xzs
	 * Revision:
	 *    2021-08-25 17:26:04 - first revision by xzs
	 *
	 */
	@AutoLog(value = "采购单（供应商）列表汇总详情")
	@ApiOperation(value="采购单（供应商）列表汇总详情", notes="采购单（供应商）列表汇总详情")
	@GetMapping(value = "/queryEntryBySupplier") 
	public Result<?> queryEntryBySupplier(StkIoBillVO stkIoBillVO,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		Page<StkEntryDetailDTO> page = new Page<StkEntryDetailDTO>(pageNo, pageSize);
		List<StkEntryDetailDTO> list = stkIoBillService.getEntryBySupplier(stkIoBillVO);
		return Result.ok(page.setRecords(list));
	}
	
	/**
	 * 采购单（供应商）列表汇总详情导出excel
	 *
	 * @param request
	 * @param stkIoBill
	 */
	@RequestMapping(value = {"/exportBillSupplierDetailXls"}) 
	public ModelAndView exportBillSupplierDetailXls(HttpServletRequest request, StkIoBillVO stkIoBillVO) {
		// Step.1 当前登录人
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<StkEntryDetailDTO> list = stkIoBillService.getEntryBySupplier(stkIoBillVO);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<StkEntryDetailDTO> dtoList = new ArrayList<StkEntryDetailDTO>();
		if(oConvertUtils.isEmpty(selections)) {
			dtoList = list;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			dtoList = list.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}


		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "采购单（供应商）列表汇总详情");
		mv.addObject(NormalExcelConstants.CLASS, StkEntryDetailDTO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("采购单（供应商）列表汇总详情", "导出人:"+sysUser.getRealname(), "采购单（供应商）列表汇总详情"));
		mv.addObject(NormalExcelConstants.DATA_LIST, dtoList);
		return mv;
	}
	
	/**
	 * @Description 商品毛利计算汇总
	 * @param stkIoBillVO
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 * Create at: 2021-08-23 16:22:47
	 * @author: xzs
	 * Revision:
	 *    2021-08-23 16:22:47 - first revision by xzs
	 *
	 */
	@AutoLog(value = "商品毛利计算汇总")
	@ApiOperation(value="商品毛利计算汇总", notes="商品毛利计算汇总")
	@GetMapping(value = "/queryGrossProfit")
	public Result<?> queryGrossProfit(StkIoBillVO stkIoBillVO,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		Page<GrossProfitSummaryDTO> page = new Page<GrossProfitSummaryDTO>(pageNo, pageSize);
		List<GrossProfitSummaryDTO> list = stkIoBillService.getGrossProfit(stkIoBillVO);
		//进行排序
		if(StringUtils.equals(column, "code")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getCode));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getCode).reversed());
			}
		}
		if(StringUtils.equals(column, "qty")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getQty));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getQty).reversed());
			}
		}
		if(StringUtils.equals(column, "settlePrice")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getSettlePrice));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getSettlePrice).reversed());
			}
		}
		if(StringUtils.equals(column, "settlePriceSum")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getSettlePriceSum));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getSettlePriceSum).reversed());
			}
		}
		if(StringUtils.equals(column, "cost")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getCost));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getCost).reversed());
			}
		}
		if(StringUtils.equals(column, "grossProfit")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getGrossProfit));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getGrossProfit).reversed());
			}
		}
		if(StringUtils.equals(column, "unitId_dictText")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getUnitId));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitSummaryDTO::getUnitId).reversed());
			}
		}
		IPage<GrossProfitSummaryDTO> pageList = page.setRecords(list);
		return Result.ok(pageList);
	}
	
	/**
	 * 商品毛利计算汇总导出excel
	 *
	 * @param request
	 * @param stkIoBill
	 */
	@RequestMapping(value = {"/exportGrossProfitXls"}) 
	public ModelAndView exportGrossProfitXls(HttpServletRequest request, StkIoBillVO stkIoBillVO) {
		// Step.1 当前登录人
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<GrossProfitSummaryDTO> list = stkIoBillService.getGrossProfit(stkIoBillVO);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<GrossProfitSummaryDTO> dtoList = new ArrayList<GrossProfitSummaryDTO>();
		if(oConvertUtils.isEmpty(selections)) {
			dtoList = list;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			dtoList = list.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}


		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "商品毛利汇总");
		mv.addObject(NormalExcelConstants.CLASS, GrossProfitSummaryDTO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商品毛利汇总", "导出人:"+sysUser.getRealname(), "商品毛利汇总"));
		mv.addObject(NormalExcelConstants.DATA_LIST, dtoList);
		return mv;
	}
	
	/**
	 * @Description 商品毛利计算汇总——明细
	 * @param stkIoBillVO
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 * Create at: 2021-08-23 17:25:22
	 * @author: xzs
	 * Revision:
	 *    2021-08-23 17:25:22 - first revision by xzs
	 *
	 */
	@AutoLog(value = "商品毛利计算汇总——明细")
	@ApiOperation(value="商品毛利计算汇总——明细", notes="商品毛利计算汇总——明细")
	@GetMapping(value = "/queryGrossProfitDetails")
	public Result<?> queryGrossProfitDetails(StkIoBillVO stkIoBillVO,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		Page<GrossProfitDetailDTO> page = new Page<GrossProfitDetailDTO>(pageNo, pageSize);
		List<GrossProfitDetailDTO> list = stkIoBillService.getGrossProfitDetail(stkIoBillVO);
		//进行排序
		if(StringUtils.equals(column, "code")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getCode));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getCode).reversed());
			}
		}
		if(StringUtils.equals(column, "qty")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getQty));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getQty).reversed());
			}
		}
		if(StringUtils.equals(column, "settlePrice")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getSettlePrice));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getSettlePrice).reversed());
			}
		}
		if(StringUtils.equals(column, "settlePriceSum")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getSettlePriceSum));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getSettlePriceSum).reversed());
			}
		}
		if(StringUtils.equals(column, "cost")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getCost));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getCost).reversed());
			}
		}
		if(StringUtils.equals(column, "grossProfit")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getGrossProfit));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getGrossProfit).reversed());
			}
		}
		if(StringUtils.equals(column, "unitId_dictText")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getUnitId));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(GrossProfitDetailDTO::getUnitId).reversed());
			}
		}
		IPage<GrossProfitDetailDTO> pageList = page.setRecords(list);
		return Result.ok(pageList);
	}
	
	/**
	 * 商品毛利汇总详情导出excel
	 *
	 * @param request
	 * @param stkIoBill
	 */
	@RequestMapping(value = {"/exportGrossProfitDetailXls"}) 
	public ModelAndView exportGrossProfitDetailXls(HttpServletRequest request, StkIoBillVO stkIoBillVO) {
		// Step.1 当前登录人
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<GrossProfitDetailDTO> list = stkIoBillService.getGrossProfitDetail(stkIoBillVO);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<GrossProfitDetailDTO> dtoList = new ArrayList<GrossProfitDetailDTO>();
		if(oConvertUtils.isEmpty(selections)) {
			dtoList = list;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			dtoList = list.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}


		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "商品毛利汇总详情");
		mv.addObject(NormalExcelConstants.CLASS, GrossProfitDetailDTO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("商品毛利汇总详情", "导出人:"+sysUser.getRealname(), "商品毛利汇总详情"));
		mv.addObject(NormalExcelConstants.DATA_LIST, dtoList);
		return mv;
	}
	
	/**
	 * @Description 客户购买商品毛利汇总
	 * @param stkIoBillVO
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 * Create at: 2021-08-25 08:54:17
	 * @author: xzs
	 * Revision:
	 *    2021-08-25 08:54:17 - first revision by xzs
	 *
	 */
	@AutoLog(value = "客户购买商品毛利汇总")
	@ApiOperation(value="客户购买商品毛利汇总", notes="客户购买商品毛利汇总")
	@GetMapping(value = "/queryCustomerGrossProfit")
	public Result<?> queryCustomerGrossProfit(StkIoBillVO stkIoBillVO,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		Page<CustomerGrossProfitDTO> page = new Page<CustomerGrossProfitDTO>(pageNo, pageSize);
		List<CustomerGrossProfitDTO> list = stkIoBillService.getCustomerGrossProfit(stkIoBillVO);
		//进行排序
		if(StringUtils.equals(column, "code")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getCode));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getCode).reversed());
			}
		}
		if(StringUtils.equals(column, "qty")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getQty));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getQty).reversed());
			}
		}
		if(StringUtils.equals(column, "settlePrice")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getSettlePrice));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getSettlePrice).reversed());
			}
		}
		if(StringUtils.equals(column, "settlePriceSum")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getSettlePriceSum));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getSettlePriceSum).reversed());
			}
		}
		if(StringUtils.equals(column, "cost")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getCost));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getCost).reversed());
			}
		}
		if(StringUtils.equals(column, "grossProfit")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getGrossProfit));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getGrossProfit).reversed());
			}
		}
		if(StringUtils.equals(column, "unitId_dictText")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getUnitId));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getUnitId).reversed());
			}
		}
		if(StringUtils.equals(column, "customerId_dictText")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getCustomerId));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossProfitDTO::getCustomerId).reversed());
			}
		}
		return Result.ok(page.setRecords(list));
	}
	
	/**
	 * 客户购买商品毛利汇总导出excel
	 *
	 * @param request
	 * @param stkIoBill
	 */
	@RequestMapping(value = {"/exportCustomerGrossProfitXls"}) 
	public ModelAndView exportCustomerGrossProfitXls(HttpServletRequest request, StkIoBillVO stkIoBillVO) {
		// Step.1 当前登录人
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<CustomerGrossProfitDTO> list = stkIoBillService.getCustomerGrossProfit(stkIoBillVO);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<CustomerGrossProfitDTO> dtoList = new ArrayList<CustomerGrossProfitDTO>();
		if(oConvertUtils.isEmpty(selections)) {
			dtoList = list;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			dtoList = list.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}


		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "客户购买商品毛利汇总");
		mv.addObject(NormalExcelConstants.CLASS, CustomerGrossProfitDTO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("客户购买商品毛利汇总", "导出人:"+sysUser.getRealname(), "客户购买商品毛利汇总"));
		mv.addObject(NormalExcelConstants.DATA_LIST, dtoList);
		return mv;
	}
	
	
	@AutoLog(value = "客户购买商品毛利汇总详情")
	@ApiOperation(value="客户购买商品毛利汇总详情", notes="客户购买商品毛利汇总详情")
	@GetMapping(value = "/customerGrossProfitDetail")
	public Result<?> queryCustomerGrossProfitDetail(StkIoBillVO stkIoBillVO,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
			HttpServletRequest req) {
		String column = req.getParameter("column");
		String order = req.getParameter("order");
		Page<CustomerGrossDetailDTO> page = new Page<CustomerGrossDetailDTO>(pageNo, pageSize);
		List<CustomerGrossDetailDTO> list = stkIoBillService.getCustomerGrossProfitDetail(stkIoBillVO);
		//进行排序
		if(StringUtils.equals(column, "code")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getCode));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getCode).reversed());
			}
		}
		if(StringUtils.equals(column, "qty")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getQty));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getQty).reversed());
			}
		}
		if(StringUtils.equals(column, "settlePrice")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getSettlePrice));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getSettlePrice).reversed());
			}
		}
		if(StringUtils.equals(column, "settlePriceSum")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getSettlePriceSum));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getSettlePriceSum).reversed());
			}
		}
		if(StringUtils.equals(column, "cost")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getCost));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getCost).reversed());
			}
		}
		if(StringUtils.equals(column, "grossProfit")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getGrossProfit));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getGrossProfit).reversed());
			}
		}
		if(StringUtils.equals(column, "unitId_dictText")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getUnitId));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getUnitId).reversed());
			}
		}
		if(StringUtils.equals(column, "customerId_dictText")) {
			if(StringUtils.equals(order, "asc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getCustomerId));
			}else if(StringUtils.equals(order, "desc")) {
				list.sort(Comparator.comparing(CustomerGrossDetailDTO::getCustomerId).reversed());
			}
		}
		return Result.ok(page.setRecords(list));
	}
	
	/**
	 * 客户购买商品毛利汇总详情导出excel
	 *
	 * @param request
	 * @param stkIoBill
	 */
	@RequestMapping(value = {"/exportCustomerGrossDetailXls"}) 
	public ModelAndView exportCustomerGrossDetailXls(HttpServletRequest request, StkIoBillVO stkIoBillVO) {
		// Step.1 当前登录人
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<CustomerGrossDetailDTO> list = stkIoBillService.getCustomerGrossProfitDetail(stkIoBillVO);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<CustomerGrossDetailDTO> dtoList = new ArrayList<CustomerGrossDetailDTO>();
		if(oConvertUtils.isEmpty(selections)) {
			dtoList = list;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			dtoList = list.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}


		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "客户购买商品毛利汇总详情");
		mv.addObject(NormalExcelConstants.CLASS, CustomerGrossDetailDTO.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("客户购买商品毛利汇总详情", "导出人:"+sysUser.getRealname(), "客户购买商品毛利汇总详情"));
		mv.addObject(NormalExcelConstants.DATA_LIST, dtoList);
		return mv;
	}
	
	/**
	 * @Description 供应商采购入库历史记录
	 * @param vo
	 * @param pageNo
	 * @param pageSize
	 * @return
	 * Create at: 2021-09-07 09:48:40
	 * @author: xzs
	 * Revision:
	 *    2021-09-07 09:48:40 - first revision by xzs
	 *
	 */
	@AutoLog(value = "供应商采购入库历史记录")
	@ApiOperation(value="供应商采购入库历史记录", notes="供应商采购入库历史记录")
	@GetMapping(value = "/queryBillBySupplier")
	public Result<?> queryBillBySupplier(StkIoBillVO vo,
			@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
			@RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		Page<StkIoBillEntryDTO> page = new Page<StkIoBillEntryDTO>(pageNo, pageSize);
		IPage<StkIoBillEntryDTO> pageList = stkIoBillEntryService.getBillEntryBySupplier(page, vo);
		return Result.ok(pageList);
	}
}
